/*
 * Alloy Analyzer
 * Copyright (c) 2002 Massachusetts Institute of Technology
 *
 * The Alloy Analyzer is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * The Alloy Analyzer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with the Alloy Analyzer; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package alloy.sharbool;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import alloy.ast.ASTDepthFirstReturnVisitor;
import alloy.ast.DeclIter;
import alloy.ast.LeafId;
import alloy.ast.Node;
import alloy.ast.VarCreator;
import alloy.ast.Variable;
import alloy.ast.VariableExpr;

/** Computes for each node the set of quantified variables
    on which that node depends -- i.e. on whose current
    values the meaning of the node depends.  This can include
    any of the quantified variables defined at the higher-up
    nodes of the AST, but does not include any quantified variables
    defined at that node or below.
    <p>
    The visit() methods return the {@link Set} of {@link LeafId}s of
    quantified {@link Variable}s used by the node. */
public class VarUseVisitor extends ASTDepthFirstReturnVisitor {
    /** {@link Map} from {@link Node} to the {@link Set} of {@link LeafId}s
	of quantified {@link Variable}s on which that node depends. */
    private Map _node2varset = new TreeMap();

    public Object visit(Node node_) {
	Set thisNodeVars = new TreeSet();
	if (node_ instanceof VariableExpr) {
	    VariableExpr varExpr_ = (VariableExpr)node_;
	    if (varExpr_.isQuantified)
		thisNodeVars.add(varExpr_.getLeafId());
	}
	for (int i=0; i<node_.numChildren(); i++)
	    thisNodeVars.addAll((Set)visit(node_.childAt(i)));
	if (node_ instanceof VarCreator) {
	    for (DeclIter declIter = new DeclIter((VarCreator)node_); declIter.hasNext();) {
		Variable var = (Variable)declIter.next();
		thisNodeVars.remove(declIter.getLeafId());
	    }
	}
	_node2varset.put(node_, thisNodeVars);
	return thisNodeVars;
    }

    public Map getNodeVars() { return _node2varset; }
}
    
